﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Utils;

namespace LevenBlog.Core.Data.Sqlite
{
    public sealed class SqliteArchive : IArchive
    {
        public int Count(IDbProvider provider)
        {
            string sql = "select count([id]) from [lb_archive]";
            return Convert.ToInt32(SqliteHelper.Instance.ExecuteScalar(provider, sql));
        }

        public void Insert(IDbProvider provider, lb_archive archive)
        {
            IDataParameter[] paras = null;
            string sql = SqliteHelper.Instance.CreateInsertSql(archive, out paras);
            SqliteHelper.Instance.ExecuteNonQuery(provider, sql, paras);
        }

        public void Update(IDbProvider provider, lb_archive archive)
        {
            IDataParameter[] paras = null;
            string sql = SqliteHelper.Instance.CreateUpdateSql(archive, out paras);
            SqliteHelper.Instance.ExecuteNonQuery(provider, sql, paras);
        }

        public void Delete(IDbProvider provider, int id)
        {
            string sql = string.Format("delete from [lb_archive] where [id]={0}", id);
            SqliteHelper.Instance.ExecuteNonQuery(provider, sql);
        }

        public void Delete(IDbProvider provider, int year, int month)
        {
            string sql = string.Format("delte from [lb_archive] where [year]={0} and [month]={1}", year, month);
            SqliteHelper.Instance.ExecuteNonQuery(provider, sql);
        }

        public lb_archive Get(IDbProvider provider, int id)
        {
            string sql = string.Format("select * from [lb_archive] where [id]={0}", id);
            using (IDataReader dr = SqliteHelper.Instance.ExecuteDataReader(provider, sql))
            {
                return SqliteHelper.Instance.ConvertToEntity<lb_archive>(dr);
            }
        }

        public lb_archive Get(IDbProvider provider, int year, int month)
        {
            string sql = string.Format("select * from [lb_archive] where [year]={0} and [month]={1}", year, month);
            using (IDataReader dr = SqliteHelper.Instance.ExecuteDataReader(provider, sql))
            {
                return SqliteHelper.Instance.ConvertToEntity<lb_archive>(dr);
            }
        }

        public IList<lb_archive> Get(IDbProvider provider)
        {
            string sql = "select * from [lb_archive] order by [id] desc";
            using (IDataReader dr = SqliteHelper.Instance.ExecuteDataReader(provider, sql))
            {
                return SqliteHelper.Instance.ConvertToList<lb_archive>(dr);
            }
        }
    }
}
